
#include<math.h>
#include<pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>

#include "Constant.h"

int routerTable[256];

pthread_mutex_t router_mutex;


void ManageRoute_init(){
	printf("ManageRoute_init\n");
	pthread_mutex_init(&router_mutex, NULL);

/*
	//----------------------gate way--------------------------------
	system("iptables -F");
	system("iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE");
	system("echo 1 >> /proc/sys/net/ipv4/ip_forward");
	routerTable[255]=255; //indicate internet addr
	routerEtx[255]=10;
	routerTTL[255]=1000000;
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*/

}



//--------------------------------del or add OS's routeTable--------------------------
void del_router(int dst){
  //printf("del_router\n");
	if(dst==255){
		while(system("route del default")==0);
		return;
	}
	
	pthread_mutex_lock( &router_mutex);
	if (routerTable[dst]!=0){
		char cmd[50];
		memset(cmd,0,sizeof(cmd));
		strcpy(cmd,"route del ");
		int i, j;
		int len=strlen(cmd);
		for(i=0,j=0;j<3;i++){
		    cmd[len++]=HOSTIP[i];
		    if(HOSTIP[i]=='.')
		        j++;
		}
		sprintf(cmd+len,"%d",dst);
	        printf("%s\n",cmd);
			
		//while(system(cmd)==0);

		system(cmd);
		
		routerTable[dst] = 0;
	}
	pthread_mutex_unlock( &router_mutex);

}

void add_router(int dst, int gw){
    //printf("add_route dst=%d gw=%d\n", dst, gw);
    pthread_mutex_lock( &router_mutex);
	if (routerTable[dst]==gw){
		pthread_mutex_unlock( &router_mutex);
		return;
	}
    pthread_mutex_unlock( &router_mutex);
	
	del_router(dst);
	//printf("after del_router\n");

	pthread_mutex_lock( &router_mutex);
	//printf("1\n");
	char cmd[50];
	memset(cmd,0,sizeof(cmd));
	int i, j,len;
	//printf("2\n");
	if(dst==255){
		strcpy(cmd,"route add default gw ");
		len=strlen(cmd);
		for(i=0,j=0;j<3;i++){
			cmd[len++]=HOSTIP[i];
			if(HOSTIP[i]=='.')
			    j++;
		}
	}
	else{
	    strcpy(cmd,"route add ");
		len=strlen(cmd);
		for(i=0,j=0;j<3;i++){
	    	cmd[len++]=HOSTIP[i];
	    	if(HOSTIP[i]=='.')
	       	 j++;
		}
		sprintf(cmd+len,"%d gw ",dst);
		len=strlen(cmd);
		for(i=0,j=0;j<3;i++){
			cmd[len++]=HOSTIP[i];
			if(HOSTIP[i]=='.')
	        	j++;
		}
	}
	//printf("4\n");
	sprintf(cmd+len,"%d",gw);
    printf("%s\n",cmd);
	system(cmd);

	routerTable[dst] = gw;
	pthread_mutex_unlock( &router_mutex);
	//printf("5\n");
}

int get_gw(int dst){
	return routerTable[dst];
}

